package wendyeq.iweb.blog.dao.impl;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import wendyeq.iweb.blog.dao.IVisitorDAO;
import wendyeq.iweb.blog.pojo.Visitor;
import wendyeq.iweb.blog.util.JdoManager;

@Component("visitorDAO")
public class VisitorDAO implements IVisitorDAO {
	private static final Logger logger = Logger.getLogger(VisitorDAO.class);
	
	/*public Visitor insert(Visitor visitor) {
		PersistenceManager manager = JdoManager.getSession();
		try{
			manager.makePersistent(visitor);
		} catch(Exception e) {
			logger.error(e);
		} finally{
			manager.close();
		}
		return visitor;
	}*/
	@Override
	public boolean saveOrUpdate(Visitor entity) {
		PersistenceManager manager = JdoManager.getSession();
		try{
			manager.makePersistent(entity);
		} catch(Exception e) {
			logger.error(e);
			return false;
		} finally{
			manager.close();
		}
		return true;
	}
	
	@Override
	public boolean delete(String id) {
		PersistenceManager manager = JdoManager.getSession();
		try{
			Visitor visitor = manager.getObjectById(Visitor.class, id);
			manager.deletePersistent(visitor);
		} catch (Exception e) {
			logger.error(e);
			return false;
		} finally {
			manager.close();
		}
		return true;
	}
	
	@Override
	public Visitor findById(String id) {
		PersistenceManager manager = JdoManager.getSession();
		Visitor visitor = null;
		try {
			visitor = manager.getObjectById(Visitor.class, id);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			manager.close();
		}
		return visitor;
	}

	@Override
	public List<Visitor> findByPage(int min, int max) {
		List<Visitor> visitors = null;
		PersistenceManager manager = JdoManager.getSession();
		try {
			Query query = manager.newQuery(Visitor.class);
			query.setOrdering("createdTime DESC");
			query.setRange(min, max);
			visitors = (List<Visitor>) query.execute();
		} catch (Exception e) {
			logger.error(e);
		}
		return visitors;
	}

	@SuppressWarnings("unchecked")
	public List<Visitor> findAll() {
		List<Visitor> visitors = null;
		PersistenceManager manager = JdoManager.getSession();
		try {
			Query query = manager.newQuery(Visitor.class);
			query.setOrdering("createdTime DESC");
			visitors = (List<Visitor>) query.execute();
		} catch (Exception e) {
			logger.error(e);
		}
		return visitors;
	}

}
